package com.Example;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import com.protos.Peer.*;

import java.net.URI;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;

public class ExampleClient extends WebSocketClient {
    public ExampleClient(URI serverUri, Draft draft) {
        super(serverUri, draft);
    }

    public ExampleClient(URI serverURI) {
        super(serverURI);
    }

    public ExampleClient( URI serverUri, Map<String, String> httpHeaders ) {
        super(serverUri, httpHeaders);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        send("连接");
        System.out.println("opened connection");
    }

    @Override
    public void onClose( int code, String reason, boolean remote ) {
        // The codecodes are documented in class org.java_websocket.framing.CloseFrame
        System.out.println( "Connection closed by " + ( remote ? "remote peer" : "us" ) + " Code: " + code + " Reason: " + reason );
    }

    @Override
    public void onMessage(String message) {
        System.out.println("received message: " + message);
    }

    @Override
    public void onMessage(ByteBuffer message) {
        try {
//            System.out.println(message.remaining());
//            byte[] bytes = new byte[message.remaining()]
//            ByteBuffer.wrap(bytes);
            byte[] bytes = new byte[message.capacity()];
            message.get(bytes, 0, bytes.length);
            Event event = Event.parseFrom(bytes);
//            System.out.println(event.getBlk());
//            Event.Action action = event.getAction();
            // 解析transactions
            List transactions = event.getBlk().getTransactionsList();
            if (!transactions.isEmpty()) {
                System.out.println(transactions.size());
                System.out.println(transactions.get(0));
                //TODO 交易签名验证
                System.out.println(event.getBlk().getPreviousBlockHash().toByteArray().toString());
            }
//            System.out.println(event.getBlk().getPreviousBlockHash().toByteArray().toString());
//            System.out.println("received ByteBuffer");
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("an error occurred:" + ex);
    }


    public static void main(String[] args) {
        //TODO websocket 订阅event事件
        String host = "192.168.2.69:8081";
        try {
            ExampleClient c = new ExampleClient( new URI( "ws://" + host + "/event" ));
            c.connect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
